package com.sunther.document.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunther.document.Enum.DictEnum;
import com.sunther.document.dao.FileSystemMidDao;
import com.sunther.document.entity.FileSystemEntity;
import com.sunther.document.entity.FileSystemMidEntity;
import com.sunther.document.entity.ProjectEntity;
import com.sunther.document.service.FileSystemMidService;
import com.sunther.document.service.FileSystemService;
import com.sunther.document.service.ProjectService;
import com.sunther.idb.common.util.WebResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author csb
 * @description: TODO
 * @date 2023/5/17 17:26
 */
@Service
public class FileSystemMidServiceImpl extends ServiceImpl<FileSystemMidDao, FileSystemMidEntity> implements FileSystemMidService {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private FileSystemService fileSystemService;

    @Override
    public List<FileSystemMidEntity> listByKeyword(String keyword) {
        QueryWrapper<FileSystemMidEntity> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(keyword)){
            wrapper.like("name",keyword);
        }
        wrapper.eq("system_type", DictEnum.SYSTEM_TYPE_TEMPLATE.getCode());

        wrapper.orderByDesc("update_time");
        List<FileSystemMidEntity> list = list(wrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WebResult delMid(String id) {

        //是否有项目引用
        QueryWrapper<ProjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("system_id",id);
        long count = projectService.count(wrapper);
        if (count > 0) {
            return WebResult.failure("有项目引用，禁止删除");
        }

        //删除详情
        QueryWrapper<FileSystemEntity> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("mid_id",id);
        fileSystemService.remove(wrapper1);

        //删除主表
        removeById(id);
        return WebResult.success("操作成功");
    }

    @Override
    public Map<String, String> getAllSystemNameByMap() {
        List<FileSystemMidEntity> list = list();
        Map<String, String> map = list.stream().collect(Collectors.toMap(FileSystemMidEntity::getId, FileSystemMidEntity::getName));
        return map;
    }
}
